package com.dream.technology.controller;

import com.dream.technology.components.riskControl.SymbolConstan;
import com.dream.technology.data.GenericRspDTO;
import com.dream.technology.data.NoBody;
import com.dream.technology.db.entity.RcFlow;
import com.dream.technology.db.entity.RcFlowQuery;
import com.dream.technology.db.entity.vo.FlowVO;
import com.dream.technology.db.entity.vo.ParentFlowVo;
import com.dream.technology.service.RcFlowItemService;
import com.dream.technology.service.RcFlowParentService;
import com.dream.technology.vo.ErrorCode;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * 描述：主流程
 *     主流程对应子流程一对多的关系
 *
 * @author chen_q_i@163.com
 * 2019/1/25 : 14:46.
 * @version : 1.0
 */
@Api("风控主流程接口")
@RestController
@RequestMapping("/risk/admin/parent_flow")
public class RcFlowParentController {

	@Autowired
    private RcFlowParentService rcFlowParentService;
    @Autowired
    private RcFlowItemService rcFlowItemService;


    /**
     * 列表接口
     * @author:wangxm
     * @Date:2019年1月25日 下午3:45:32
     * @param pageNum
     * @param pageSize
     * @param flowName
     * @return
     */
    @GetMapping("/list")
    public GenericRspDTO<Object> getList(Integer pageNum, Integer pageSize, String flowName) {
        RcFlowQuery query = new RcFlowQuery();
        RcFlowQuery.Criteria criteria1 = query.createCriteria();
        RcFlowQuery.Criteria criteria2 = query.createCriteria();
        criteria1.andStatusEqualTo(false);
        criteria1.andFlowTypeEqualTo(SymbolConstan.FLOW_TYPE_PARENT);
        if (StringUtils.isNotBlank(flowName)){
            criteria1.andFlowNameLike("%" + flowName + "%");
            criteria2.andFlowCodeLike("%" + flowName + "%");
        }
        query.or(criteria2);
        query.setOrderByClause("enabled desc,create_date desc");
        PageHelper.startPage(pageNum, pageSize);
        List<RcFlow> rcFlowList = rcFlowParentService.selectByExample(query);
        PageInfo<RcFlow> pageInfo = new PageInfo<RcFlow>(rcFlowList);
        // 请求配置中心
        List<Long> nameList = new ArrayList<Long>();
        List<RcFlow> flowList = pageInfo.getList();
        flowList.forEach(flow -> {
        	nameList.add(flow.getId());
        });
//        Map<Long, String> items = adminClient.getAllProductUsedModel(JSON.toJSONString(nameList), "WindControl", null);
    	List<FlowVO> newList = new ArrayList<FlowVO>();
        flowList.forEach(flow ->{
        	FlowVO record = new FlowVO();
            try {
                BeanUtils.copyProperties(record, flow);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
//        	if (items != null) {
//        		record.setBorrowingProductUsed(items.get(flow.getId()));
//        	}
        	newList.add(record);
        });
        PageInfo<FlowVO> page = new PageInfo<FlowVO>();
        page.setList(newList);
        page.setTotal(pageInfo.getTotal());
        page.setPageNum(pageNum);
        page.setPageSize(pageSize);
        return GenericRspDTO.newInstance(ErrorCode.SUCCESS.getErrorCode(), ErrorCode.SUCCESS.getErrorMsg(), page);
    }
    
    /**
     * 创建总流程
     * @author:wangxm
     * @Date:2019年1月25日 下午3:49:15
     * @param flowName
     * @param flowDetail
     * @param enabled
     * @return
     */
    @PostMapping("/add")
    public GenericRspDTO<Object> add(String flowName, String flowDetail, Boolean enabled) {
    	rcFlowParentService.add(flowName, flowDetail, enabled);
        return GenericRspDTO.newInstance(ErrorCode.SUCCESS.getErrorCode(), ErrorCode.SUCCESS.getErrorMsg(), null);
    }
    
    /**
     * 风控总流程回显
     * @author:wangxm
     * @Date:2019年1月25日 下午3:56:24
     * @param id
     * @return
     */
    @GetMapping("/id")
    public GenericRspDTO<ParentFlowVo> getById(Long id) {
        ParentFlowVo flowVo = new ParentFlowVo();
        flowVo.setFlow(rcFlowParentService.selectByPrimaryKey(id));
        flowVo.setRcFlowItems(rcFlowItemService.selectByFlowId(id));
        return GenericRspDTO.newInstance(ErrorCode.SUCCESS.getErrorCode(), ErrorCode.SUCCESS.getErrorMsg(), flowVo);
    }
    
    /**
     * 编辑总流程
     * @author:wangxm
     * @Date:2019年1月25日 下午6:49:21
     * @param id
     * @param flowName
     * @param flowDetail
     * @param enabled
     * @return
     */
    @PostMapping("/update")
    public GenericRspDTO<Object> modify(Long id, String flowName, String flowDetail, Boolean enabled) {
    	RcFlow record = new RcFlow();
    	record.setId(id);
    	record.setFlowName(flowName);
    	record.setFlowDetail(flowDetail);
    	record.setEnabled(enabled);
    	rcFlowParentService.updateByPrimaryKeySelective(record);
        return GenericRspDTO.newInstance(ErrorCode.SUCCESS.getErrorCode(), ErrorCode.SUCCESS.getErrorMsg(), null);
    }
    
    /**
     * 配置总流程
     * @author:wangxm
     * @Date:2019年1月28日 上午10:28:12
     * @param rcFlowStr
     * @return
     */
    @PostMapping("/config")
    public GenericRspDTO<Object> config(@RequestBody ParentFlowVo rcFlowStr) {

    	rcFlowParentService.updateByJsonStr(rcFlowStr);

        return GenericRspDTO.newInstance(ErrorCode.SUCCESS.getErrorCode(), ErrorCode.SUCCESS.getErrorMsg(), null);
    }
    
    /**
     * 删除或停用风控总流程(逻辑删除)
     * @author:wangxm
     * @Date:2019年1月28日 上午10:43:22
     * @param id
     * @param status
     * @param enabled
     * @return
     */
    @PostMapping("/deleteOrStop")
    public GenericRspDTO<NoBody> delete(Long id, Boolean status, Boolean enabled) {
    	RcFlow flow = new RcFlow();
    	flow.setId(id);
        if (status != null) {
        	flow.setStatus(status);
		}
		if (enabled != null) {
			flow.setEnabled(enabled);
		}
		rcFlowParentService.updateByPrimaryKeySelective(flow);
        return GenericRspDTO.newInstance(ErrorCode.SUCCESS.getErrorCode(), ErrorCode.SUCCESS.getErrorMsg(), null);
    }
    
    /**
     * 复制风控总流程
     * @author:wangxm
     * @Date:2019年1月28日 上午10:44:59
     * @param id
     * @param flowName
     * @param flowDetail
     * @param enabled
     * @return
     */
    @PostMapping("/copy")
    public GenericRspDTO<Object> copy(Long id, String flowName, String flowDetail, Boolean enabled) {
    	rcFlowParentService.copy(id, flowName, flowDetail, enabled);
        return GenericRspDTO.newInstance(ErrorCode.SUCCESS.getErrorCode(), ErrorCode.SUCCESS.getErrorMsg(), null);
    }
    
    /**
     * 规则表达式生成文本描述
     * @author:wangxm
     * @Date:2019年1月28日 上午10:56:08
     * @param flowExp
     * @return
     */
    @PostMapping("/checkForDoc")
    public GenericRspDTO<Object> checkFlow( @RequestBody ParentFlowVo flowExp) {
        String result = rcFlowParentService.checkFlow(flowExp);
        return GenericRspDTO.newInstance(ErrorCode.SUCCESS.getErrorCode(), ErrorCode.SUCCESS.getErrorMsg(), result);
    }
    
    /**
     * 操作总流程前检查是否被金融产品引用
     * @author:wangxm
     * @Date:2019年1月28日 上午10:56:52
     * @param flowId
     * @return
     */
    @PostMapping("/checkRef")
    public GenericRspDTO<Object> checkFlowRef(Long flowId) {
    	List<Long> nameList = new ArrayList<Long>();
    	nameList.add(flowId);
//    	Map<Long, String> items = adminClient.getAllProductUsedModel(JSON.toJSONString(nameList), "WindControl", null);
//    	if (items != null && items.size() > 0) {
//    		return GenericRspDTO.newInstance(ErrorCode.SUCCESS.getErrorCode(), ErrorCode.SUCCESS.getErrorMsg(), items.get(flowId));
//    	}
        return GenericRspDTO.newInstance(ErrorCode.SUCCESS.getErrorCode(), ErrorCode.SUCCESS.getErrorMsg(), null);
    }
    
    /**
     * 验证风控总流程名称是否重复
     * @author:wangxm
     * @Date:2019年1月28日 上午10:59:32
     * @param name
     * @return
     */
    @GetMapping("/getByName")
    public GenericRspDTO<Object> getByName(String name){
    	RcFlowQuery query = new RcFlowQuery();
    	RcFlowQuery.Criteria criteria = query.createCriteria();
    	criteria.andFlowNameEqualTo(name);
    	criteria.andFlowTypeEqualTo(SymbolConstan.FLOW_TYPE_PARENT);
    	int count = rcFlowParentService.selectByExample(query).size();
    	return GenericRspDTO.newInstance(ErrorCode.SUCCESS.getErrorCode(), ErrorCode.SUCCESS.getErrorMsg(), count);
    }
    
    /**
     * 查询可用的子流程集合
     * @author:wangxm
     * @Date:2019年1月28日 下午3:10:47
     * @return
     */
    @GetMapping("/getFlowSonList")
    public GenericRspDTO<Object> getFlowSonList(){
    	RcFlowQuery query = new RcFlowQuery();
    	RcFlowQuery.Criteria criteria = query.createCriteria();
    	criteria.andFlowTypeEqualTo(SymbolConstan.FLOW_TYPE_SON);
    	criteria.andEnabledEqualTo(true);
    	criteria.andStatusEqualTo(false);
    	List<RcFlow> list = rcFlowParentService.selectByExample(query);
    	return GenericRspDTO.newInstance(ErrorCode.SUCCESS.getErrorCode(), ErrorCode.SUCCESS.getErrorMsg(), list);
    }
    
}
